package cn.lyjuan.android.mylibrary.view.recycler;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by chad on 06/11/2017.
 */

public class DividerItemDecoration extends AbstractItemDecoration
{
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state)
    {
        if (this.cache.orientation == VERTICAL_LIST)
        {
            drawVertical(c, parent);
        } else
        {
            drawHorizontal(c, parent);
        }

    }

    public void drawVertical(Canvas c, RecyclerView parent)
    {
        if (null == this.cache.verticalDivider)
            return;

        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + this.cache.verticalDividerHeight;
            this.cache.verticalDivider.setBounds(left, top, right, bottom);
            this.cache.verticalDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent)
    {
        if (null == this.cache.horizontalDivider)
            return;
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + this.cache.horizontalDividerWidth;
            this.cache.horizontalDivider.setBounds(left, top, right, bottom);
            this.cache.horizontalDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
    {
        if (this.cache.orientation == VERTICAL_LIST)
        {
            outRect.set(0, 0, 0, this.cache.verticalDividerHeight);
        } else
        {
            outRect.set(0, 0, this.cache.horizontalDividerWidth, 0);
        }
    }
}